package com.lemzdo.mail.product.exception;

import com.lemzdo.common.exception.BizCodeEnume;
import com.lemzdo.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;


/**
 * 集中处理异常
 */
@Slf4j
/*@ControllerAdvice
@ResponseBody*/
@RestControllerAdvice(basePackages = "com.lemzdo.mail.product.controller")
public class MailExceptionControllerAdvice {

    /**
     * 集中处理校验相关的异常
     * MethodArgumentNotValidException 表示校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){

        //日志记录一下异常
        log.error("数据校验出现问题{}，异常类型{}",e.getMessage(),e.getClass());
        //获取BindingResult
        BindingResult result = e.getBindingResult();
        //遍历拿出所有的错误消息 打包放入map 返回
        Map<String,String> errMap = new HashMap<>();
        result.getFieldErrors().forEach((err)->{
            errMap.put(err.getField(),err.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",errMap);
    }

    /**
     * 通用处理
     */
    @ExceptionHandler(Throwable.class)
    public R handleException(Throwable throwable){
        log.error("错误：",throwable);
       return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
